package by.grsu.bso.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import by.grsu.bso.form.RegisterForm;
import by.grsu.bso.model.User;
import by.grsu.bso.service.ServiceManager;

public class RegisterAction extends Action {
	
	private final static String SUCCESS = "success";
	private final static String FAILURE = "failure";

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		
		RegisterForm rf = (RegisterForm) form;
		
		if ( ServiceManager.getUserService().isSame(rf.getName()) == true ) {
			response.sendRedirect("info_pages/user_is_exist.jsp");
			return mapping.findForward(FAILURE);
		} else{
		
		User user = new User(null , 2, rf.getName(), rf.getPassword(), false, rf.getFirstName(), rf.getLastName(), rf.getAddress(), rf.getTelephone());
		
		//protection
		if (user.getLogin() == null) {
			response.sendRedirect("info_pages/not_exist.jsp");
			return mapping.findForward(FAILURE);
		}
		
		ServiceManager.getUserService().saveUser(user);
		
		return mapping.findForward(SUCCESS);
		}
	}
	
	

}
